package com.ext.aic.components;

import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ext.aic.R;
import com.ext.aic.beans.response.AppUpdateBody;
import com.ext.aic.events.OnAppUpdateListener;
import com.eyinfo.mpkv.MPLocalKV;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.king.app.updater.callback.AppUpdateCallback;
import com.lxj.xpopup.core.CenterPopupView;

import java.io.File;

import lombok.Setter;

public class AppUpdatePopup extends CenterPopupView {

    private Button updateBtn;
    private LinearProgressIndicator progressLpi;
    private TextView updateProgressTipTv;

    @Setter
    private OnAppUpdateListener onAppUpdateListener;

    public AppUpdatePopup(Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.app_update_layout;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        TextView contentTv = findViewById(R.id.content_tv);
        Button laterBtn = findViewById(R.id.later_btn);
        updateBtn = findViewById(R.id.update_btn);
        progressLpi = findViewById(R.id.progress_lpi);
        updateProgressTipTv = findViewById(R.id.update_progress_tip_tv);

        contentTv.setText(getUpdateContent());

        laterBtn.setOnClickListener(this::onLaterClick);
        updateBtn.setOnClickListener(this::onUpdateClick);
        updateBtn.setEnabled(true);

        if (isForceUpdate()) {
            laterBtn.setVisibility(View.GONE);
            progressLpi.setVisibility(View.VISIBLE);
            updateProgressTipTv.setVisibility(View.VISIBLE);
        } else {
            laterBtn.setVisibility(View.VISIBLE);
            laterBtn.setEnabled(true);
            progressLpi.setVisibility(View.GONE);
            updateProgressTipTv.setVisibility(View.GONE);
        }
    }

    private String getUpdateContent() {
        if (onAppUpdateListener == null) {
            return "";
        }
        Context context = getContext();

        AppUpdateBody body = onAppUpdateListener.getAppUpdateBody();
        return context.getString(R.string.update_version_format, body.getVersion()) + "\n" +
                body.getContent();
    }

    private boolean isForceUpdate() {
        if (onAppUpdateListener != null) {
            return onAppUpdateListener.isForceUpdate();
        }
        return false;
    }

    public void onUpdateClick(View view) {
        if (onAppUpdateListener != null) {
            onAppUpdateListener.onAppUpdate(appUpdateCallback);
        }
    }

    public void onLaterClick(View view) {
        MPLocalKV.getInstance().put("pauseCheckUpdateTime", System.currentTimeMillis());
        dismiss();
    }

    private AppUpdateCallback appUpdateCallback = new AppUpdateCallback() {
        @Override
        public void onStart(String url) {
            if (isForceUpdate()) {
                progressLpi.setProgress(0);
                updateProgressTipTv.setText(R.string.downloading_text);
                updateBtn.setEnabled(false);
            } else {
                dismiss();
            }
        }

        @Override
        public void onProgress(long progress, long total, boolean isChanged) {
            if (isChanged && isForceUpdate()) {
                int percentage = (int) (progress * 1.0 / total * 100);
                progressLpi.setProgress(percentage, true);
                updateProgressTipTv.setText(String.format("%s%%", percentage));
            }
        }


        @Override
        public void onFinish(File file) {
            if (isForceUpdate()) {
                progressLpi.setProgress(100);
                updateProgressTipTv.setText(R.string.download_complete);
                CountDownTimer countDownTimer = new CountDownTimer(10000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        // 直接使用主线程 Handler
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (getContext() == null) return;
                                String downloadComplete = getContext().getString(R.string.download_complete);
                                updateProgressTipTv.setText(
                                        String.format("%s（%s）", downloadComplete, millisUntilFinished / 1000)
                                );
                            }
                        });
                    }

                    @Override
                    public void onFinish() {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (getContext() == null) return;
                                progressLpi.setProgress(0);
                                updateProgressTipTv.setText(R.string.downloading_text);
                                updateBtn.setEnabled(true);
                            }
                        });
                    }
                };
                countDownTimer.start();
            }
        }
    };
}
